<template>
  <div class="full-management">
    <div class="page-header">
      <h2>满减管理</h2>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :model="searchForm" inline>
        <el-form-item label="满减名称">
          <el-input v-model="searchForm.fullName" placeholder="请输入满减名称" clearable />
        </el-form-item>
        <el-form-item label="满减类型">
          <el-select v-model="searchForm.fullType" placeholder="请选择满减类型" clearable>
            <el-option label="小额满减" :value="1" />
            <el-option label="大额满减" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="满减范围">
          <el-select v-model="searchForm.fullScope" placeholder="请选择满减范围" clearable>
            <el-option label="适用于小额满减" :value="1" />
            <el-option label="适用于大额满减" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="满减状态">
          <el-select v-model="searchForm.fullState" placeholder="请选择状态" clearable>
            <el-option label="进行中" :value="1" />
            <el-option label="已终止" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchFulls">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="primary" @click="showAddDialog = true">
            <el-icon><Plus /></el-icon>
            新增满减
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table :data="fullList" v-loading="loading" stripe>
        <el-table-column prop="fullId" label="满减ID" width="80" />
        <el-table-column prop="fullName" label="满减名称" width="200" />
        <el-table-column prop="fullType" label="满减类型" width="120">
          <template #default="{ row }">
            <el-tag :type="row.fullType === 1 ? 'success' : 'warning'">
              {{ getFullTypeText(row.fullType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="fullScope" label="满减范围" width="150">
          <template #default="{ row }">
            <el-tag :type="row.fullScope === 1 ? 'primary' : 'info'">
              {{ getFullScopeText(row.fullScope) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="fullCon" label="满减条件" width="200" show-overflow-tooltip />
        <el-table-column prop="fullState" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStateType(row.fullState)">
              {{ getStateText(row.fullState) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="180" />
        <el-table-column prop="endTime" label="结束时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="editFull(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="deleteFull(row.fullId)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="isEdit ? '编辑满减' : '新增满减'"
      v-model="showAddDialog"
      width="600px"
      @close="resetForm"
    >
      <el-form :model="fullForm" :rules="fullRules" ref="fullFormRef" label-width="120px">
        <el-form-item label="满减名称" prop="fullName">
          <el-input v-model="fullForm.fullName" placeholder="请输入满减名称" />
        </el-form-item>
        <el-form-item label="满减类型" prop="fullType">
          <el-select v-model="fullForm.fullType" placeholder="请选择满减类型">
            <el-option label="小额满减" :value="1" />
            <el-option label="大额满减" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="满减范围" prop="fullScope">
          <el-select v-model="fullForm.fullScope" placeholder="请选择满减范围">
            <el-option label="适用于小额满减" :value="1" />
            <el-option label="适用于大额满减" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="满减条件" prop="fullCon">
          <el-input v-model="fullForm.fullCon" type="textarea" placeholder="请输入满减条件" />
        </el-form-item>
        <el-form-item label="满减状态" prop="fullState">
          <el-select v-model="fullForm.fullState" placeholder="请选择状态">
            <el-option label="进行中" :value="1" />
            <el-option label="已终止" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="fullForm.startTime"
            type="datetime"
            placeholder="请选择开始时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="fullForm.endTime"
            type="datetime"
            placeholder="请选择结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue'
import { fullApi } from '@/api/full'

// 响应式数据
const loading = ref(false)
const fullList = ref([])
const showAddDialog = ref(false)
const isEdit = ref(false)
const fullFormRef = ref()

// 搜索表单
const searchForm = reactive({
  fullName: '',
  fullType: null,
  fullScope: null,
  fullState: null
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 满减表单
const fullForm = reactive({
  fullId: null,
  fullName: '',
  fullType: null,
  fullScope: null,
  fullCon: '',
  fullState: null,
  startTime: '',
  endTime: ''
})

// 表单验证规则
const fullRules = {
  fullName: [
    { required: true, message: '请输入满减名称', trigger: 'blur' }
  ],
  fullType: [
    { required: true, message: '请选择满减类型', trigger: 'change' }
  ],
  fullScope: [
    { required: true, message: '请选择满减范围', trigger: 'change' }
  ],
  fullCon: [
    { required: true, message: '请输入满减条件', trigger: 'blur' }
  ],
  fullState: [
    { required: true, message: '请选择满减状态', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ]
}

// 获取满减类型文本
const getFullTypeText = (type) => {
  const typeMap = {
    1: '小额满减',
    2: '大额满减'
  }
  return typeMap[type] || '未知'
}

// 获取满减范围文本
const getFullScopeText = (scope) => {
  const scopeMap = {
    1: '适用于小额满减',
    2: '适用于大额满减'
  }
  return scopeMap[scope] || '未知'
}


// 获取状态类型
const getStateType = (state) => {
  const stateMap = {
    1: 'success',
    2: 'danger'
  }
  return stateMap[state] || 'info'
}

// 获取状态文本
const getStateText = (state) => {
  const stateMap = {
    1: '进行中',
    2: '已终止'
  }
  return stateMap[state] || '未知'
}

// 搜索满减
const searchFulls = async () => {
  loading.value = true
  try {
    const response = await fullApi.getFullList(searchForm)
    if (response.code === 200) {
      fullList.value = response.data || []
      pagination.total = fullList.value.length
    }
  } catch (error) {
    console.error('搜索满减失败:', error)
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    fullName: '',
    fullType: null,
    fullScope: null,
    fullState: null
  })
  searchFulls()
}

// 编辑满减
const editFull = (row) => {
  isEdit.value = true
  Object.assign(fullForm, row)
  showAddDialog.value = true
}

// 删除满减
const deleteFull = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个满减活动吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await fullApi.deleteFull(id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      searchFulls()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除满减失败:', error)
    }
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await fullFormRef.value.validate()

    const response = isEdit.value
      ? await fullApi.updateFull(fullForm)
      : await fullApi.addFull(fullForm)

    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '修改成功' : '新增成功')
      showAddDialog.value = false
      searchFulls()
    }
  } catch (error) {
    console.error('提交失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(fullForm, {
    fullId: null,
    fullName: '',
    fullType: null,
    fullScope: null,
    fullCon: '',
    fullState: null,
    startTime: '',
    endTime: ''
  })
  isEdit.value = false
  fullFormRef.value?.resetFields()
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  searchFulls()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  searchFulls()
}

// 初始化
onMounted(() => {
  searchFulls()
})
</script>

<style scoped>
.full-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-area {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-area {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
